<?php
class directResize {
	
	function directResize($config)
	{
		$this->labels_list = array("drthumbonly", "drskip");
		$this->SetConfig($config);
	}
	//-------------------------------------------------------------------------------------------------
	function SetConfig($config)
	{
		global $modx;
		
		if (file_exists($modx->config["base_path"].DIRECTRESIZE_PATH."configs/$config.config.php"))
			@include_once $modx->config["base_path"].DIRECTRESIZE_PATH."configs/$config.config.php";
		
		$local_parms = array(
			"tpl_thumb" 						=> '[+dr.shortcut.source2thumb+]',
			"tpl_lightbox" 						=> '<a href="[+dr.big.src+]" target="_blank">[+dr.shortcut.tpl_thumb+]</a>',
			"header" 							=> "",
			"thumb_resize_method" 				=> 0,
			"big_resize_method" 				=> 3,
			"thumbonly" 						=> false,
			"skip" 								=> false,
			"big_quality" 						=> 75,
			"thumb_quality" 					=> 75,
			"thumb_width" 						=> 120,
			"thumb_height" 						=> 90,
			"thumb_use_defaults" 				=> 0,
			"big_width" 						=> 800,
			"big_height" 						=> 600,
			"crop_dir" 							=> "C",
			"thumb_watermark_type"				=> false, 
			"thumb_watermark_align"				=> "BR",
			"thumb_watermark_margin"			=> "5x5",
			"thumb_watermark_text"				=> "Filesize: ^Fkkb",
			"thumb_watermark_text_color"		=> "FFFFFF",
			"thumb_watermark_font_size"			=> 5,
			"thumb_watermark_bg_color"			=> "",
			"thumb_watermark_bg_opacity"		=> 100,
			"thumb_watermark_bg_directions"		=> "",
			"thumb_watermark_ttf_file"			=> "",
			"thumb_watermark_opacity"			=> 100,
			"thumb_watermark_rotation"			=> 0,
			"thumb_watermark_img"				=> "",
			"big_watermark_type"				=> false, 
			"big_watermark_align"				=> "BR",
			"big_watermark_margin"				=> "5x5",
			"big_watermark_text"				=> "Filesize: ^Fkkb",
			"big_watermark_text_color"			=> "FFFFFF",
			"big_watermark_font_size"			=> 5,
			"big_watermark_bg_color"			=> "",
			"big_watermark_bg_opacity"			=> 100,
			"big_watermark_bg_directions"		=> "",
			"big_watermark_ttf_file"			=> "",
			"big_watermark_opacity"				=> 100,
			"big_watermark_rotation"			=> 0,
			"big_watermark_img"					=> "",
			"bind_config_to_path"				=> false,
			"bind_config_to_document_template"	=> false,
			"bind_config_to_css_selector"		=> false,
			"thumb_phpthumb_parms"				=> false,
			"big_phpthumb_parms"				=> false,
		);
		
		foreach ($local_parms as $key => $val) 
		{
			if (isset($dr_local[$key]))
			{
				$array_val = is_array($dr_local[$key]) ? $dr_local[$key] : array("all" => $dr_local[$key]);// : 
			}
			else
			{
				$array_val = array("all" => $val);
			}
			$this->drconfig[$key] = array_merge(array("all" => $val), $array_val);
		}
		
		$global_parms = array(
			"path" 								=> "assets/images",	
			"phpthumb_path"						=> "assets/snippets/phpthumb/",
			"bindings_priority"					=> "label,css,template,path",
			"furl"								=> true,
			"furl_prefix"						=> "images/",
			"image_processor"					=> "image.php",
		);		
		
		foreach ($global_parms as $key => $val) {
			$this->drglobal[$key] = isset($dr_global[$key]) ? $dr_global[$key] : $val;
		}

		define(PHPTHUMB_PATH, $this->drglobal["phpthumb_path"]);
		define(DR_IMAGE_PROCESSOR, $modx->config["site_url"].$this->drglobal["image_processor"]);
	}
	//-------------------------------------------------------------------------------------------------
	function OriginalImgSize()
	{
		$file = getimagesize($this->absolutePath($this->current["source"]["src"]));
		$file["width"]	= $file[0];
		$file["height"] = $file[1];	
		return $file;
	}
	//-------------------------------------------------------------------------------------------------
	function CalculateFinalSizes()
	{
		global $modx;
		
		$img_prop = $this->current["file"]["width"] / $this->current["file"]["height"];
		
		if ($this->current["process_mode"] == "thumb")
			$resize_method = $this->current["config"]["thumb_resize_method"];
			
		if ($this->current["process_mode"] == "big") 
			$resize_method = $this->current["config"]["big_resize_method"];
		
		if ($this->current["target"]["height"] == 0) $resize_method = 1;
		if ($this->current["target"]["width"] == 0) $resize_method = 2;
				
		$calculated_width =  round($this->current["target"]["height"] * $img_prop);
		$calculated_height =  round($this->current["target"]["width"] / $img_prop);
				
		switch ($resize_method){
			case 0:
			
				if ($calculated_height > $this->current["target"]["height"]) 
				{
					$diff = $calculated_height  - $this->current["target"]["height"];
					$this->current["phpthumb_parms"]["h"] = $calculated_height;
					$this->current["phpthumb_parms"]["w"] = round($calculated_height * $img_prop);
					$this->SetCropParm($this->current["config"]["crop_dir"], $diff, false);
				}
				else
				{
					$diff = $calculated_width  - $this->current["target"]["width"];
					
					$this->current["phpthumb_parms"]["w"] = $calculated_width;
					$this->current["phpthumb_parms"]["h"] = round($calculated_width / $img_prop);
					$this->SetCropParm($this->current["config"]["crop_dir"], $diff, true);
				}
				break;
			case 1:
				$this->current["target"]["height"] = $calculated_height;
				$this->current["phpthumb_parms"]["h"] = $this->current["target"]["height"];
				break;
			case 2:
				$this->current["target"]["width"] = $calculated_width;
				$this->current["phpthumb_parms"]["w"] = $this->current["target"]["width"];
				break;
			case 3:
				if ($img_prop > 1)
				{
					if ($this->current["target"]["height"] > $calculated_height) $this->current["target"]["height"] = $calculated_height;
					$this->current["target"]["width"] = round($this->current["target"]["height"] * $img_prop);
					$this->current["phpthumb_parms"]["h"] = $this->current["target"]["height"];
					
				}
				else
				{
					if ($this->current["target"]["width"] > $calculated_width) $this->current["target"]["width"] = $calculated_width;
					$this->current["target"]["height"] = round($this->current["target"]["width"] / $img_prop);
					$this->current["phpthumb_parms"]["w"] = $this->current["target"]["width"];
				}
				break;
		}
		
	}
	//-------------------------------------------------------------------------------------------------
	function SetCropParm($dir, $diff, $landscape)
	{
		if ($landscape)
			$search = array("T", "B");
		else
			$search = array("L", "R");

		$dir = str_replace($search, "", $dir);
		
		switch ($dir){
			
			case "T":
				$this->current["phpthumb_parms"]['fltr_crop'] = "0|0|0|{$diff}";
				break;
				
			case "B":
				$this->current["phpthumb_parms"]['fltr_crop'] = "0|0|{$diff}|0";
				break;
				
			case "L":
				$this->current["phpthumb_parms"]['fltr_crop'] = "0|{$diff}|0|0";
				break;
				
			case "R":
				$this->current["phpthumb_parms"]['fltr_crop'] = "{$diff}|0|0|0";
				break;
				
			case "C":
				$diff_1 = round($diff / 2);
				$diff_2 = $diff - $diff_1;
				if ($landscape)
					$this->current["phpthumb_parms"]['fltr_crop'] = "{$diff_1}|{$diff_2}|0|0";
				else
					$this->current["phpthumb_parms"]['fltr_crop'] = "0|0|{$diff_1}|{$diff_2}";
				break;
		}
	}
	
	//-------------------------------------------------------------------------------------------------
	function ApplyWatermark()
	{
		global $modx;
		
		$watermark_parms = array(
			"watermark_type", 
			"watermark_align",
			"watermark_margin",
			"watermark_text",
			"watermark_text_color",
			"watermark_font_size",
			"watermark_bg_color",
			"watermark_bg_opacity",
			"watermark_bg_directions",
			"watermark_ttf_file",
			"watermark_opacity",
			"watermark_rotation",
			"watermark_img"
		);
		
		$prefix = $this->current["process_mode"]."_";

		if ($this->current["config"][$prefix."watermark_type"] == "image" || $this->current["config"][$prefix."watermark_type"] == "text")
			foreach($watermark_parms as $w_parm)
			{
				 $watermark[$w_parm] = $this->current["config"][$prefix.$w_parm];
			}
		
		if ($watermark["watermark_type"] == "image"){
			list($x,$y) = explode("x", $this->current["config"]["watermark_margin"]);
			$this->current["phpthumb_parms"]["fltr_wmi"]=$watermark["watermark_img"]."|".$watermark["watermark_align"]."|".$watermark["watermark_opacity"]."|".$x."|".$y."|".$watermark["watermark_rotation"];			
		}
		
		if ($watermark["watermark_type"] == "text"){
			$text = urlencode(htmlentities($watermark["watermark_text"], ENT_QUOTES, $modx->config["modx_charset"]));
			$this->current["phpthumb_parms"]["fltr_wmt"]=$text."|".$watermark["watermark_font_size"]."|".$watermark["watermark_align"]."|".$watermark["watermark_text_color"]."|".$watermark["watermark_ttf_file"].
			"|".$watermark["watermark_opacity"]."|".$watermark["watermark_margin"]."|".$watermark["watermark_rotation"]."|".$watermark["watermark_bg_color"]."|".$watermark["watermark_bg_opacity"]."|".$watermark["watermark_bg_directions"];
		}
	}

	//-------------------------------------------------------------------------------------------------
	function checkPath()
	{
		if (!@getimagesize($this->absolutePath($this->current["source"]["src"]))) return false;
		
		$rules = str_replace("\r", "",$this->drglobal["path"]);
		$rules = explode("\n", $rules);
		
		foreach($rules as $val)
		{
			if (strlen(trim($val))>0)
			{
				if (substr($val,0,1) == "!") 
				{
					$tmp = $this->absolutePath(substr($val, 1, strlen($val)));
					if ($tmp) $rule["deny"][] = $tmp;
				}
				else
				{
					$tmp = $this->absolutePath($val);
					if ($tmp) $rule["allow"][] =$tmp;
				}
			}
		}
		$path = $this -> absolutePath(dirname($this->current["source"]["src"]));
				
		$longest_deny_path = "";
		if (is_array($rule["deny"]))
			foreach ($rule["deny"] as $r)
			{
				if (substr($path, 0, strlen($r)) == $r && strlen($r) > strlen($longest_deny_path))  
					$longest_deny_path = $r; 
			}
			
		$longest_allow_path = "";
		if (is_array($rule["allow"]))
			foreach ($rule["allow"] as $r)
			{
				if (substr($path, 0, strlen($r)) == $r && strlen($r) > strlen($longest_allow_path))  
				{
					$longest_allow_path = $r;
				}
			}
			
		$result = strlen($longest_deny_path) > strlen($longest_allow_path) ? false : $longest_allow_path;	
		return $result;
	}
	//-------------------------------------------------------------------------------------------------
	function _checkTemplateBindings()
	{
		global $modx;
		foreach ($this->drconfig["bind_config_to_document_template"] as $config_name => $binded_template_id) {
			if ($modx->documentObject["template"] == $binded_template_id)
			{
				return $config_name;
			}
		}
	}
	//-------------------------------------------------------------------------------------------------
	function _checkPathBindings()
	{
		$path = $this->current["longest_allowed_path"];
		foreach ($this->drconfig["bind_config_to_path"] as $config_name => $binded_path) {
			$binded_path = $this -> absolutePath($binded_path);
			if (substr($path, 0, strlen($binded_path)) == $binded_path && strlen($binded_path) > strlen($longest_binded_path))
			{  
				$longest_binded_path = $binded_path;
				$current_config_name = $config_name;
			} 
		}
		return $current_config_name; 
	}
	//-------------------------------------------------------------------------------------------------
	function _removeSiteUrl($path)
	{
		global $modx;
		$path = str_replace($modx->config["site_url"], "", $path);
		return $path;
	}
	//-------------------------------------------------------------------------------------------------
    function absolutePath($path) 
    {
        global $modx;
    	$path = $this->_removeSiteUrl($path);
        if (strstr($path, "://"))  return $path;
	    if (substr($path, 0, 1) == "/" || $modx->isBackend())
	        $basePath= $_SERVER['DOCUMENT_ROOT'];
	    else
	        $basePath= dirname($_SERVER['SCRIPT_FILENAME']);
	    
	    $absPath= realpath("{$basePath}/{$path}");
	    if (substr($absPath,strlen($absPath)-1,1) == "/" || substr($absPath,strlen($absPath)-1,1) == "\\") $absPath = substr($absPath,0 ,strlen($absPath)-1);
	    return $absPath;
    }
	//-------------------------------------------------------------------------------------------------
	function SetTargetSizes()
	{	
		if ($this->current["process_mode"] == "thumb")
		{
			
			$target["height"] = $this->current["source"]["height"];
			$target["width"] = $this->current["source"]["width"];
			
			switch ($this->current["config"]["thumb_use_defaults"]) {
				case 1:
					if ($this->current["source"]["height"] == 0 && $this->current["source"]["width"] == 0 && $this->current["config"]["thumb_height"] > 0 &&  $this->current["config"]["thumb_width"] > 0)
					{
						$target["height"] = $this->current["config"]["thumb_height"];
						$target["width"] = $this->current["config"]["thumb_width"];
					}
				break;
				
				case 2:
					if ($this->current["source"]["width"] == 0 && $this->current["config"]["thumb_width"] > 0)
					{
						$target["width"] = $this->current["config"]["thumb_width"];
					}
				break;
				
				case 3:
					if ($this->current["source"]["height"] == 0 && $this->current["source"]["height"] == 0)
					{
						$target["height"] = $this->current["config"]["thumb_height"];
					}
				break;	
				
				case 4:
					if ($this->current["config"]["thumb_height"] > 0 &&  $this->current["config"]["thumb_width"] > 0)
					{
						$target["height"] = $this->current["config"]["thumb_height"];
						$target["width"] = $this->current["config"]["thumb_width"];
					}
				break;					
			}
		}
		
		if ($this->current["process_mode"] == "big")
		{
			$target["width"] = $this->current["file"]["width"] > $this->current["config"]["big_width"] ? $this->current["config"]["big_width"] : $this->current["file"]["width"];
			$target["height"] = $this->current["file"]["height"] > $this->current["config"]["big_height"] ? $this->current["config"]["big_height"] : $this->current["file"]["height"];
		}
		
		return $target;
	}
	//-------------------------------------------------------------------------------------------------
	function LabelsRemove($content)
	{
		$pattern = implode("\s*|\s*", $this->labels_list);
		$pattern .= "\s*|\s*(drconfig|drcss)_\w+";
		return preg_replace("/\s*{$pattern}\s*/si", "", $content);
	}
	//-------------------------------------------------------------------------------------------------
	function LabelsCheck()
	{
		$has_label = array();
		$img = $this->current["img_tag"];
		
		foreach ($this->labels_list as $v)
		{
			preg_match("/".$v."/i",$img,$match);
			$has_label[$v] = $match[0] == $v ? TRUE : FALSE;
		}
		if (preg_match("/(drconfig|drcss)_(\w+)/i",$img,$match)) $has_label[$match[1]] = $match[2];
		return $has_label;
	}
	//-------------------------------------------------------------------------------------------------
	function PHPThumbQueryStr()
	{
		global $PHPTHUMB_CONFIG, $modx;
		@require_once($modx->config["base_path"].PHPTHUMB_PATH."phpThumb.config.php");
		
		$path_info = pathinfo($this->current["source"]["src"]);
		
		$format = strtolower($path_info["extension"]);
		$format = $format == "jpg" ? "jpeg" : $format;
		$this->current["phpthumb_parms"]["f"] = $format;
		
		if ($this->current["process_mode"] == "thumb") 
		{
			$prefix = "thumb_";
			$this->current["phpthumb_parms"]["q"] = $this->current["config"]["thumb_quality"];
			$phpthumb_parms_name = "thumb_phpthumb_parms";
		}
		else
		{
			$this->current["phpthumb_parms"]["q"] = $this->current["config"]["big_quality"];
			$phpthumb_parms_name = "big_phpthumb_parms";
		}
		
		$this->current["phpthumb_parms"]["sia"]=$prefix.basename($this->current["source"]["src"]);
		
		$qry = "&src=".$this->_removeSiteUrl($this->current["source"]["src"]);
		
		foreach ($this->current["phpthumb_parms"] as $key => $val)
		{
			if (strstr($key, "fltr_"))
			{
				$val = str_replace("fltr_", "", $key).(empty($val) ? "" : "|").$val;
				$key = "fltr[]";
			}
			
			$qry .="&{$key}={$val}";
		}
		
		if (is_array($this->current["config"][$phpthumb_parms_name]))
			foreach ($this->current["config"][$phpthumb_parms_name] as $key => $val)
				if (is_array($val))
				{
					foreach ($val as $v) {
						$qry .="&{$key}[]={$v}";
					}
				}
				else
				{
					$qry .="&{$key}={$val}";
				}
		
		if ($PHPTHUMB_CONFIG['high_security_enabled'])
		{
			$hash = md5($qry.$PHPTHUMB_CONFIG['high_security_password']);
			$qry .= '&hash='.$hash;
		}
		  
		$qry = DR_IMAGE_PROCESSOR."?".$qry;
		
		if ($this->drglobal["furl"] && !$modx->isBackend())
		{
			$furl_id = md5($qry);
			$_SESSION["dr"][$furl_id] = $qry;
			$furl_prefix =  substr($this->drglobal["furl_prefix"], -1) == "/" ?  $this->drglobal["furl_prefix"] : $this->drglobal["furl_prefix"]."/";
			$qry = $furl_prefix.$furl_id."/".$this->current["phpthumb_parms"]["sia"];
		}
		
		unset($this->current["phpthumb_parms"]);
		return $qry;
	}
	//-------------------------------------------------------------------------------------------------
	function GetCurrentConfig()
	{
		return $this->_getCurrentConfigParms($this->_getCurrentConfigName());
	}
	//-------------------------------------------------------------------------------------------------
	function _getCurrentConfigName()
	{
		$priority = preg_split("/\s*,\s*/", $this->drglobal["bindings_priority"]);
		
		if ($this->current["labels"]["drconfig"]) $has_config["label"] = true;
		if ($this->drconfig["bind_config_to_path"]) $has_config["path"] = true;
		if ($this->drconfig["bind_config_to_document_template"]) $has_config["template"] = true;
		if ($this->drconfig["bind_config_to_css_selector"]) $has_config["css"] = true;
		
		foreach ($priority as $config_type)
		{
			if ($has_config[$config_type])
			{
				switch ($config_type) {
					case "label":
						$config_name = $this->current["labels"]["drconfig"];
					break;
					
					case "path":
						$config_name = $this->_checkPathBindings();
					break;
					
					case "template":
						$config_name = $this->_checkTemplateBindings();;
					break;	
					
					case "css":
						$config_name = $this->current["labels"]["drcss"];
					break;
				}
				if ($config_name) break;
			}
		}
		return $config_name;
	}	
	//-------------------------------------------------------------------------------------------------
	function _getCurrentConfigParms($config_name = "all")
	{
		if (is_array($this->used_configs[$config_name]))
		{
			$current_config = $this->used_configs[$config_name];
		}
		else 
		{
			foreach ($this->drconfig as $key => $val)
			{
				$current_config[$key] = $this->drconfig[$key][$config_name] ? $this->drconfig[$key][$config_name] : $this->drconfig[$key]["all"];
			}
			$this->used_configs[$config_name] = $current_config;
		}
		
		return $current_config;
	}
	//-------------------------------------------------------------------------------------------------
	function _getSourceImgAttr()
	{
		preg_match_all("/(src|height|width|alt|title|class|valign|align|style|hspace|vspace|border)\s*=\s*(['\"])(.*?)\\2/i", $this->current["img_tag"], $match);
		$result =  array_combine($match[1],$match[3]);
		
		if ($result["style"])
		{
			preg_match_all("/(width|height)\s*:\s*([0-9]+)px/i", $result["style"], $match);
			if (!empty($match[1])) $result_style =  array_combine($match[1],$match[2]);
			if (is_array($result_style)) $result = array_merge($result, $result_style);
		}
		return $result;
	}
	//-------------------------------------------------------------------------------------------------
	function _setCSSBindingLabel($content)
	{
		global $modx;
		@require_once $modx->config["base_path"].DIRECTRESIZE_PATH."includes/simple_html_dom.php";
		$html = new simple_html_dom();
		$html->load($content);
		
		foreach($this->drconfig["bind_config_to_css_selector"] as $cname => $path)
		{
			foreach($html->find($path) as $img_tag)
				if ($path) $img_tag->attr["title"] = $img_tag->attr["title"] ? $img_tag->attr["title"]." drcss_".$cname : "drcss_".$cname;
		}
		$content = $html->outertext;
		$html->clear();
		unset($html);
		return $content;
	}
	//-------------------------------------------------------------------------------------------------
	function ConvertFromBackend($content)
	{
		global $modx;
			
			$s = array("/", ".");
			$r = array("\\/", "\.");
			$url = str_replace($s, $r, "{$this->drglobal["image_processor"]}|".DR_IMAGE_PROCESSOR."");
			
			$pattern = "<img[^>]*src=(['\"])(({$url}).*?src=([^&]*?)&.*?)\\1[^>]*>";
			
			$content =  preg_replace_callback("/{$pattern}/si",
			create_function(
	           '$matches',
	           'return str_replace($matches[2], $matches[4], $matches[0]);'
			),
			$content); 
			
			$content = preg_replace("/\s*drcss_\w+\s*/", "", $content);
			
			return $content;
	}
	//-------------------------------------------------------------------------------------------------
	function _canProcessThumb()
	{
		return $this->current["source"]["width"] > 0 || $this->current["source"]["height"] > 0 || $this->current["target"]["width"] > 0 || $this->current["target"]["height"] > 0;
	}
	//-------------------------------------------------------------------------------------------------
	function _canProcessBig()
	{
		global $modx;
		return !$modx->isBackend() && !$this->current["labels"]["drthumbonly"] && !$this->current["config"]["thumbonly"] &&
		($this->current["source"]["height"] < $this->current["file"]["height"] || $this->current["source"]["width"] < $this->current["file"]["width"]);
	}
	//-------------------------------------------------------------------------------------------------
	function _canProcessImage()
	{		
		if ($this->current["labels"]["drskip"]) return false;
		$this->current["longest_allowed_path"] = $this->checkPath();	
		return $this->current["longest_allowed_path"];
	}	
	//-------------------------------------------------------------------------------------------------
	function Process($content)
	{
		global $modx;

		if ($this->drconfig["bind_config_to_css_selector"])
		{
			$content = $this->_setCSSBindingLabel($content);
		}
		
		preg_match_all("/<img[^>]*>/", $content, $imgs); 
		$imgs_all = $imgs[0];
		
		for($n=0;$n<count($imgs_all);$n++)
		{
			$this->current = array();
			
			$this->current["iteration"] = $n;
			
			$this->current["img_tag"] = $imgs_all[$n];
			$this->current["labels"]  = $this->LabelsCheck();
			$this->current["source"]  = $this->_getSourceImgAttr();
			
			if ($this->_canProcessImage())
			{
				$this->current["config"] = $this->GetCurrentConfig();
				
				if ($this->current["config"]["skip"]) continue; 
				
				$this->current["process_mode"] = "thumb";
				$this->current["target"] = $this->SetTargetSizes();
				
				if ($this->_canProcessThumb())
				{
					$this->current["file"] = $this->OriginalImgSize();
					
					$this->CalculateFinalSizes();
					$this->ApplyWatermark();
					$this->current["target"]["src"] = $this->PHPThumbQueryStr();
					$this->current["thumb"] = $this->current["target"];
					unset($this->current["target"]);
					
					$this->current["parsed"]["thumb"] = $this->ParseTemplate($this->current["config"]["tpl_thumb"]);

					$this->current["process_mode"] = "big";
					$this->current["target"] = $this->SetTargetSizes();
					
					if ($this->_canProcessBig())
					{	
						$this->CalculateFinalSizes();
						$this->ApplyWatermark();
						$this->current["target"]["src"] = $this->PHPThumbQueryStr();
						$this->current["big"] = $this->current["target"];
						unset($this->current["target"]);
						
						$this->current["parsed"]["big"] = $this->ParseTemplate($this->current["config"]["tpl_lightbox"]);
						
					}
					
					if ($this->current["parsed"]["big"]) 
					{
						$this->addHead = true;
						$new_tpl = $this->current["parsed"]["big"];
					}
					else
					{
						$new_tpl = $this->current["parsed"]["thumb"];
					}
					$content = str_replace($this->current["img_tag"], $new_tpl, $content);	
				}
			}
		}
		
		if (!$modx->isBackend()) 
		{
			$content = $this->LabelsRemove($content);
			if ($this->addHead) $content = $this->AddHeadCssJs($content);
		}
		
		return $content;
	}
	//-------------------------------------------------------------------------------------------------
	function ParseTemplate($tpl)
	{
		global $modx;
		
		if ($modx->isBackend())  $tpl = "[+dr.shortcut.source2thumb+]";
		
		if (!class_exists('DRChunkie')) {
			require_once($modx->config["base_path"].DIRECTRESIZE_PATH."includes/chunkie.class.inc.php");
		}	

		$drtemplate = new DRChunkie($tpl);
		
		$context 							= array();
		$context["source"]					= $this->current["source"];
		$context["thumb"] 					= $this->current["thumb"];
		$context["big"] 					= $this->current["big"];
		$context["shortcut"]["tpl_thumb"] 	= $this->current["parsed"]["thumb"];
		$context["id"] 						= $this->current["iteration"];

		if (strstr($tpl, "[+dr.shortcut.source2thumb+]"))
		{
			$source_tag = preg_replace_callback("/(src|height|width)=(['\"])(.*?)\\2/i", 
			create_function(
	           '$matches',
	           'return "$matches[1]=$matches[2][+dr.thumb.$matches[1]+]$matches[2]";'
			),
			$this->current["img_tag"]); 
			
			if ($this->current["source"]["style"])
			{
				$source_style_tag  = preg_replace_callback("/(width|height)\s*:\s*[0-9]+px/i", 
				create_function(
		           '$matches',
		           'return "$matches[1]: [+dr.thumb.$matches[1]+]px";'
				),
				$this->current["source"]["style"]); 
				$source_tag = str_replace($this->current["source"]["style"], $source_style_tag, $source_tag);			
			}			
			$context["shortcut"]["source2thumb"] = $source_tag;
		}
		
		$drtemplate->addVar('dr', $context);
		
		return $drtemplate->Render();	
	}
	//-------------------------------------------------------------------------------------------------
	function AddHeadCssJs($content)
	{
	    $head =  $this->drconfig["header"]["all"];
	    unset($this->used_configs["all"]);
	    if (is_array($this->used_configs))
		    foreach ($this->used_configs as $key => $val)
		    {
		    	$head .= $this->drconfig["header"][$key];
		    }
	    return preg_replace("/(\<\/head\>)/i", $head."\\1", $content);
	}
}

?>